const dbUser = require("../../db/db_user")();

/* 接收post请求 */
function parsePostData(ctx) {
  return new Promise((resolve, reject) => {
    try {
      let postdata = "";
      ctx.req.on("data", data => {
        postdata += data;
        // console.log(String(postdata));
      });
      ctx.req.addListener("end", function() {
        resolve(postdata);
      });
    } catch (error) {
      reject(error);
    }
  });
}

module.exports = function() {
  return async function(ctx, next) {
    // 允许来自所有域名请求
    ctx.set("Access-Control-Allow-Origin", "*");
    // 这样就能只允许 http://localhost:8080 这个域名的请求了
    // ctx.set("Access-Control-Allow-Origin", "http://localhost:8080");

    // 设置所允许的HTTP请求方法
    ctx.set("Access-Control-Allow-Methods", "OPTIONS, GET, PUT, POST, DELETE");

    // 字段是必需的。它也是一个逗号分隔的字符串，表明服务器支持的所有头信息字段.
    ctx.set(
      "Access-Control-Allow-Headers",
      "x-requested-with, accept, origin, content-type"
    );
    ctx.set("content-type", "application/json; charset=UTF-8");

    let isExist = await parsePostData(ctx)
      .then(async postData => {
        console.log(postData);
        postData = JSON.parse(postData);
        let userInfo = await dbUser
          .findUserName(postData.userName)
          .then(result => {
            return result[0];
          });
        console.log(postData);
        console.log(`userInfo = ${userInfo}`);
        if (userInfo) {
          if (
            postData.userName == userInfo.userName &&
            postData.password == userInfo.password
          ) {
            return true;
          } else {
            return false;
          }
        } else {
          return false;
        }
      })
      .then(result => {
        console.log(result);
        return result;
      });
    let result = isExist ? 1 : "用户名或者密码错误";

    ctx.body = { result: result };
  };
};
